package com.cfswt.tasksystem.controller;

import com.cfswt.tasksystem.mapper.ToolAttachmentMapper;
import com.cfswt.tasksystem.mapper.ToolOrderItemMapper;
import com.cfswt.tasksystem.mapper.ToolOrderMapper;
import com.cfswt.tasksystem.pojo.dto.ApprovalCommentDTO;
import com.cfswt.tasksystem.pojo.dto.PlanToolOrderItemDTO;
import com.cfswt.tasksystem.pojo.dto.ToolOrderItemDTO;
import com.cfswt.tasksystem.pojo.entity.PlanOrderItemWrapper;
import com.cfswt.tasksystem.pojo.entity.ToolAttachment;
import com.cfswt.tasksystem.pojo.entity.ToolOrder;
import com.cfswt.tasksystem.pojo.vo.*;
import com.cfswt.tasksystem.response.JsonResult;
import com.cfswt.tasksystem.security.CustomUserDetails;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.activiti.api.runtime.shared.query.Page;
import org.activiti.api.runtime.shared.query.Pageable;
import org.activiti.api.task.model.Task;
import org.activiti.api.task.model.builders.TaskPayloadBuilder;
import org.activiti.api.task.runtime.TaskRuntime;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.impl.identity.Authentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/tool")
@Api(tags = "50.搅拌工具模块")
public class ToolController {
    @Autowired
    private ToolOrderMapper toolOrderMapper;
    @Autowired
    private ToolOrderItemMapper toolOrderItemMapper;
    @Autowired
    private ToolAttachmentMapper toolAttachmentMapper;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private TaskRuntime taskRuntime;
    @Autowired
    private TaskService taskService;

    @ApiOperation(value = "全部工具订单")
    @GetMapping("/allOrderList")
    public JsonResult selectAllOrder() {
        List<ToolOrderListVO> toolOrderListVOS = toolOrderMapper.selectOrderList();
        return JsonResult.ok(toolOrderListVOS);
    }

    @ApiOperation(value = "我的订单")
    @GetMapping("/myOrderList/")
    public JsonResult selectOrderForUser(@AuthenticationPrincipal CustomUserDetails userDetails) {
        List<ToolOrderListVO> toolOrderListVOS = toolOrderMapper.selectOrderListByUser(userDetails.getNickName());
        return JsonResult.ok(toolOrderListVOS);
    }

    @ApiOperation(value = "新建搅拌工具订单")
    @PostMapping("/addOrder")
    @Transactional
    public JsonResult addToolOrder(@RequestBody ToolOrder toolOrder, @AuthenticationPrincipal CustomUserDetails userDetails) {
        String bussinessKey = "搅拌头订单-" + userDetails.getNickName();
        String nickName = userDetails.getNickName();
        String creator = userDetails.getUsername();
        Map<String, Object> variables = new HashMap<>();
        variables.put("creator", creator);
        Authentication.setAuthenticatedUserId(userDetails.getNickName());
        String processInstanceId = runtimeService.startProcessInstanceByKey("Process_6", bussinessKey, variables).getProcessInstanceId();
        String taskId = null;
        org.activiti.engine.task.Task userTask = taskService.createTaskQuery().processInstanceId(processInstanceId).taskAssignee(creator).singleResult();
        System.out.println("Task Name: " + userTask);
        if ("创建订单".equals(userTask.getName())) {
            taskId = userTask.getId();
            Authentication.setAuthenticatedUserId(nickName);
            taskRuntime.complete(TaskPayloadBuilder.complete().withTaskId(userTask.getId()).build());
        }
        toolOrder.setProcessInstanceId(processInstanceId);
        double totalMoney = 0.00;
        int totalQuantity = 0;
        // 先计算总金额和总数量
        for (ToolOrderItemDTO item : toolOrder.getToolOrderItemDTOS()) {
            totalMoney += item.getAmountMoney();
            totalQuantity += item.getNumber();
        }
        // 设置总金额和总数量
        String orderSN = generateOrderSN();
        toolOrder.setSn(orderSN);
        toolOrder.setAmountMoney(totalMoney);
        toolOrder.setQuantity(totalQuantity);
        toolOrder.setCreateTime(new Date());
        toolOrder.setCreateBy(userDetails.getNickName());
        toolOrder.setStatus("订单审批中");
        // 插入 toolOrder 到数据库
        toolOrderMapper.addToolOrder(toolOrder);
        // 处理每个订单项和附件
        for (ToolOrderItemDTO toolOrderItemDTO : toolOrder.getToolOrderItemDTOS()) {
            toolOrderItemDTO.setOrderId(toolOrder.getId());
            toolOrderItemMapper.addToolOrderItem(toolOrderItemDTO);

            List<ToolAttachment> toolAttachments = toolOrderItemDTO.getToolAttachments();
            for (ToolAttachment toolAttachment : toolAttachments) {
                toolAttachment.setOrderId(toolOrder.getId());
                toolAttachment.setOrderItemId(toolOrderItemDTO.getId());
                toolAttachment.setCreateTime(new Date());
                toolAttachment.setCreateBy(userDetails.getNickName());
                toolAttachment.setType("产品精加工图纸");
                toolAttachmentMapper.addToolAttachment(toolAttachment);
            }
        }
        ToolAttachment toolContractAttachment = toolOrder.getContract();
        toolContractAttachment.setOrderId(toolOrder.getId());
        toolContractAttachment.setCreateTime(new Date());
        toolContractAttachment.setCreateBy(userDetails.getNickName());
        toolContractAttachment.setType("订单合同");
        toolAttachmentMapper.addToolAttachment(toolContractAttachment);
        return JsonResult.ok();
    }

    private String generateOrderSN() {
        // 获取当前日期
        LocalDate today = LocalDate.now();
        // 格式化日期为 yyyyMMdd 格式
        String formattedDate = today.format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        // 查询今天已经生成的订单数量
        Integer todayCount = toolOrderMapper.countOrdersByDate(today);
        // 生成流水号，确保是两位数，不足前面补0
        String serialNumber = String.format("%02d", todayCount + 1);
        // 拼接成完整的订单编号，以 'T' 开头
        return "T" + formattedDate + serialNumber;
    }

    @ApiOperation(value = "待审批订单信息")
    @Transactional
    @GetMapping("/showOrderApprovalVO/{taskId}")
    public JsonResult showApprovalOrderBytaskId(@PathVariable String taskId) {
        System.out.println(taskId);
        Task task = taskRuntime.task(taskId);
        ToolOrderApprovalVO toolOrderApprovalVO = toolOrderMapper.selectToolOrderApprovalVOByProcessInstanceId(task.getProcessInstanceId());
        toolOrderApprovalVO.setContract(toolAttachmentMapper.selectToolAttachmentVOByOrderId(toolOrderApprovalVO.getId()));
        List<ToolOrderItemApprovalVO> toolOrderItemApprovalVOS = toolOrderItemMapper.selectToolOrderItemApprovalVOByOrderId(toolOrderApprovalVO.getId());
        for (ToolOrderItemApprovalVO toolOrderItemApprovalVO : toolOrderItemApprovalVOS) {
            Integer toolOrderItemApprovalVOId = toolOrderItemApprovalVO.getId();
            List<ToolAttachmentVO> toolAttachmentVOList = toolAttachmentMapper.selectToolAttachmentVOByItemId(toolOrderItemApprovalVOId);
            List<ToolAttachmentVO> collect = toolAttachmentVOList.stream().filter(toolAttachmentVO -> "产品精加工图纸".equals(toolAttachmentVO.getType()))
                    .collect(Collectors.toList());
            toolOrderItemApprovalVO.setToolAttachmentVOS(collect);
        }
        toolOrderApprovalVO.setToolOrderItemApprovalVOS(toolOrderItemApprovalVOS);
        System.out.println(toolOrderApprovalVO);
        return JsonResult.ok(toolOrderApprovalVO);
    }

    @ApiOperation(value = "市场部审核")
    @Transactional
    @PostMapping("/mApproval/{taskId}")
    public JsonResult mApprovalOrder(@PathVariable String taskId,
                                     @RequestBody ApprovalCommentDTO approvalCommentDTO,
                                     @AuthenticationPrincipal CustomUserDetails userDetails) {
        System.out.println(taskId + approvalCommentDTO);
        String comment = approvalCommentDTO.getComment();
        String processInstanceId = taskRuntime.task(taskId).getProcessInstanceId();
        String nickName = userDetails.getNickName();
        Authentication.setAuthenticatedUserId(nickName);
        taskService.addComment(taskId, processInstanceId, comment);
        taskRuntime.complete(TaskPayloadBuilder.complete().withTaskId(taskId).build());
        return JsonResult.ok();
    }

    @ApiOperation(value = "公司领导审核")
    @Transactional
    @PostMapping("/gmApproval/{taskId}/{sn}")
    public JsonResult gmApprovalOrder(@PathVariable String taskId,
                                      @PathVariable String sn,
                                      @RequestBody ApprovalCommentDTO approvalCommentDTO,
                                      @AuthenticationPrincipal CustomUserDetails userDetails) {
        String comment = approvalCommentDTO.getComment();
        String processInstanceId = taskRuntime.task(taskId).getProcessInstanceId();
        String nickName = userDetails.getNickName();
        Authentication.setAuthenticatedUserId(nickName);
        taskService.addComment(taskId, processInstanceId, comment);
        taskRuntime.complete(TaskPayloadBuilder.complete().withTaskId(taskId).build());
        toolOrderMapper.updateOrderStatusBysn("制造中", sn);
        return JsonResult.ok();
    }

    @ApiOperation(value = "显示选择加工单位")
    @GetMapping("/showOrderPlanVO/{taskId}")
    public JsonResult showOrderBytaskId(@PathVariable String taskId) {
        Task task = taskRuntime.task(taskId);
        ToolOrderPlanVO toolOrderPlanVO = toolOrderMapper.selectToolOrderPlanVOByProcessInstanceId(task.getProcessInstanceId());
        List<ToolOrderItemPlanVO> toolOrderItemPlanVOS = toolOrderItemMapper.selectToolOrderItemPlanVOByOrderId(toolOrderPlanVO.getId());
        for (ToolOrderItemPlanVO toolOrderItemPlanVO : toolOrderItemPlanVOS) {
            Integer toolOrderItemPlanVOId = toolOrderItemPlanVO.getId();
            List<ToolAttachmentVO> toolAttachmentVOList = toolAttachmentMapper.selectToolAttachmentVOByItemId(toolOrderItemPlanVOId);
            List<ToolAttachmentVO> collect = toolAttachmentVOList.stream().filter(toolAttachmentVO -> "产品精加工图纸".equals(toolAttachmentVO.getType()))
                    .collect(Collectors.toList());
            toolOrderItemPlanVO.setToolAttachmentVOS(collect);
        }
        toolOrderPlanVO.setToolOrderItemPlanVOS(toolOrderItemPlanVOS);
        System.out.println(toolOrderPlanVO);
        return JsonResult.ok(toolOrderPlanVO);
    }

    @ApiOperation(value = "生产管理信息显示")
    @GetMapping("/showAllItemForProduction")
    public JsonResult showAllOrderItem() {
        List<ToolOrderItemManagementVO> toolOrderItemManagementVOS = toolOrderItemMapper.selectToolOrderItemManagementVO();
        System.out.println(toolOrderItemManagementVOS);
        return JsonResult.ok(toolOrderItemManagementVOS);
    }

    /*    @GetMapping("/tool/orderDetails/sn")
        public JsonResult showOrderItemDetail(@PathVariable String sn){
            List<ToolOrderItemApprovalVO> toolOrderItemApprovalVOS = toolOrderItemMapper.selectToolOrderItemApprovalVOBySn(sn);
            return JsonResult.ok(toolOrderItemApprovalVOS);

        }*/
    @ApiOperation(value = "确定加工单位")
    @Transactional
    @PostMapping("/updateProductionPlan/")
    public JsonResult updateProductionPlan(@RequestBody PlanOrderItemWrapper planOrderItemWrapper,
                                           @AuthenticationPrincipal CustomUserDetails userDetails) {
        List<PlanToolOrderItemDTO> planToolOrderItemDTOS = planOrderItemWrapper.getPlanToolOrderItemDTOS();
        String comment = planOrderItemWrapper.getApprovalCommentDTO().getComment();
        for (PlanToolOrderItemDTO planToolOrderItemDTO : planToolOrderItemDTOS) {
            toolOrderItemMapper.updatePlanToolOrderItemByItemId(planToolOrderItemDTO);
        }
        String processInstanceId = toolOrderMapper.selectProcessInstanceIdByOrderId(planToolOrderItemDTOS.get(0).getOrderId());
        String taskId = null;
        Page<Task> tasks = taskRuntime.tasks(Pageable.of(0, 100), TaskPayloadBuilder.tasks().withProcessInstanceId(processInstanceId).build());
        for (Task task : tasks.getContent()) {
            System.out.println("Task Name: " + task.getName());
            if ("确定加工单位".equals(task.getName())) {
                taskId = task.getId();
                Authentication.setAuthenticatedUserId(userDetails.getNickName());
                taskService.addComment(taskId, processInstanceId, comment);
                taskRuntime.complete(TaskPayloadBuilder.complete().withTaskId(task.getId()).build());
                break;
            }
        }
        return JsonResult.ok();
    }

    @GetMapping("/orderItem")
    public JsonResult selectOrderItem() {
        List<ToolOrderItemChartsVO> toolOrderItemChartsVOS = toolOrderItemMapper.selectToolOrderItemCharts();
        return JsonResult.ok(toolOrderItemChartsVOS);
    }
}
